﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Tools.Log;
using System.Web.Security;
namespace Lion.WeiXin.Controllers
{
   
    public class VipCardController : Controller
    {
        DBContext db = new DBContext();

        [PermissionFilter]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string name, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示           
            List<VipCardModel> list = db.VipCards.GetList(string.Empty);
            int totalCount = list.Count;
            //如果传入条件参数
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(n => n.Code.Contains(name)).OrderByDescending(n => n.AID).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                list = list.OrderByDescending(n => n.AID).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }
          [PermissionFilter]
        public ActionResult Show(int ID)
        {
            if (ID == 0)
            {
                return Redirect(Request.RawUrl);
            }
            VipCardModel model = db.VipCards.GetModel(ID);

            // 查询角色数据  //卡类型  code =103
          //  InitSelect(model.CardType, "103", "selCardLevel");
            //卡状态   code =101
            InitSelect(model.Dic_State, "101", "selState");
          //  InitSelect(model.Dic_CardLevel, "108", "selCardType");

            //只保留 二级菜单
            return View(model);
        }
          [PermissionFilter]
        public ActionResult Create()
        {
            // 默认初始值
            InitSelect("108001", "108", "selCardType");  //卡类型
            InitSelect("103001", "103", "selCardLevel"); //卡等级
            return View();
        }


        /// <summary>
        /// 初始化字典类型
        /// </summary>
        /// <param name="selectID"></param>
        /// <param name="dicKey"></param>
        private void InitSelect(string selectID, string dicKey, string dataKey)
        {
            //加载产品类型
            List<DictionaryModel> selectItems = db.Dictionarys.GetList(" Dic_Key like '" + dicKey + "%'");
            List<SelectListItem> selectTypes = new List<SelectListItem>();
            selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });
            foreach (DictionaryModel item in selectItems)
            {
                if (item.Dic_Key == dicKey) { continue; }//本身节点不需要
                if (item.Dic_Key == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Dic_Key.ToString(), Text = item.Dic_Value, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Dic_Key.ToString(), Text = item.Dic_Value });
                }
            }
            ViewData[dataKey] = selectTypes;
        }

          [PermissionFilter]
        public JsonResult Save(VipCardModel model)
        {
            ActionEnum saveAction = ActionEnum.Create;
            if (model.AID > 0)
            {
                saveAction = ActionEnum.Update;
            }
            string result = string.Empty;
            //储值卡无过期时间
            if (model.Dic_CardType == "108001")
            {
                model.EndDate = DataKeysModel.Instance.EndDate;
            }
            else if (model.Dic_CardType == "108002")
            {
                //计次卡
                model.Dic_CardLevel = "103000";  //一个默认值，表示非等级卡
            }
            model.Could_Buy = model.Could_Buy.TrimEnd(',');
            if (saveAction == ActionEnum.Create)
            {
                //开卡时，初始密码888888
                if (!db.VipCards.Exists(model.Code))
                {
                    model.Dic_State = "101001"; //使用
                    model.Password = FormsAuthentication.HashPasswordForStoringInConfigFile("888888", "MD5");
                    model.CreateDate = DateTime.Now;
                    model.Last_Update_Date = DateTime.Now;
                    model.Last_Changed_By = CurrentUser.UserName;
                    model.Creator = CurrentUser.UserName;                 
                    if (db.VipCards.Add(model)>0)
                    {
                        return Json(new { code = SaveStateEnum.OK.ToString(), msg = "保存成功!" });
                    }
                    else {
                        return Json(new { code = SaveStateEnum.NO.ToString(), msg = "保存失败，请稍后重试!" });
                    }
                }
                else
                {
                    return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号已存在!" });
                }

            }
            else if (saveAction == ActionEnum.Update)
            {
                VipCardModel editModel = db.VipCards.GetModel(model.AID);
                editModel.Dic_State = model.Dic_State;
                editModel.Phone = model.Phone;
                editModel.RealName = model.RealName;
                editModel.Remark = model.Remark;
                editModel.Last_Update_Date = DateTime.Now;
                editModel.Last_Changed_By = CurrentUser.UserName;
                editModel.Birthday = model.Birthday;
                if (db.VipCards.Update(editModel))
                {
                    return Json(new { code = SaveStateEnum.OK.ToString(), msg = "保存成功!" });
                }
                else
                {
                    return Json(new { code = SaveStateEnum.NO.ToString(), msg = "保存失败，请稍后重试!" });
                }
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "非创建模式和添加模式！" });
            }
        }
        [PermissionFilter]
        public JsonResult Delete(string IDs)
        {
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    IDs = IDs.TrimEnd(',');
                    //先判断卡是否被使用，被使用是不能进行删除
                    List<VipCardModel> list = db.VipCards.GetList(1, "v.AID in (" + IDs + ") and v.Total>0","v.AID");
                    if (list.Count == 0)
                    {                       
                        db.VipCards.DeleteList(IDs);
                        return Json(new { code = SaveStateEnum.OK.ToString(), msg = "删除成功" });
                    }
                    else
                    {
                        return Json(new { code = SaveStateEnum.NO.ToString(), msg = "此卡已经投入使用，不能直接删除，请更改状态为删除！" });
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
               
            }
            return Json(new { code = SaveStateEnum.NO.ToString(), msg = "删除失败,请稍后重试！" });
        }

          [PermissionFilter]
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        public JsonResult ResetPassword(string code)
        {
            string password = FormsAuthentication.HashPasswordForStoringInConfigFile("888888", "MD5");
            int rows = db.VipCards.ResetPassword(code, password);
            if (rows > 0)
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "更改成功!" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号不存在!" });
            }
        }
          [PermissionFilter]
         [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Recharge(string code)
        {
            VipCardModel model = new VipCardModel();
            if (!string.IsNullOrEmpty(code))
            {
                model = db.VipCards.GetModel(code);
                if (model.Dic_CardType == ((int)CardTypeEnum.计次卡).ToString())
                {
                    return View("Index");
                }
            }

            return View(model);
        }

         [ActionName("Recharge"), AcceptVerbs(HttpVerbs.Post)]
        /// <summary>
        /// 充值金额
        /// </summary>
        /// <param name="code">充值卡号</param>
        /// <param name="money">本次充值金额</param>
        /// <returns></returns>
        public JsonResult RechargeMoney(string code, decimal money)
        {
            if (string.IsNullOrEmpty(code))
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号为空!" });
            }
            VipCardModel model = db.VipCards.GetModel(code);
            if (model == null)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号不存在!" });
            }
            if (model.Dic_CardType == ((int)CardTypeEnum.计次卡).ToString())
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "计次卡不能充值!" });
            }

            //当前等级
            DictionaryModel curVipLevel = db.Dictionarys.GetModel(model.Dic_CardLevel);
            //下一个等级
            DictionaryModel nextVipLevel = GetNextVipCardType(curVipLevel, model.Recharge + money);
            string levelMsg = "";
            if (curVipLevel.AID != nextVipLevel.AID)
            {
                //升级了
                levelMsg = string.Format("恭喜，您的会员卡升级为{0},将享受{1}折优惠!", nextVipLevel.Dic_Value, nextVipLevel.Parameter);
                model.Dic_CardType = nextVipLevel.Dic_Key;
            }

            model.Recharge = model.Recharge + money;
            model.Balance = model.Balance + money;
            model.Last_Update_Date = DateTime.Now;
            model.Last_Changed_By = CurrentUser.UserName;
            if (db.VipCards.Update(model))
            {
                //下发短信提示
                if (Config.IsOpenSMS)
                {
                    Sms.ISendSms isend = new Sms.SendSMS();
                    isend.SendMsg(model.Phone, string.Format("【美好时光】卡号:{0}成功充值{1}当前余额:{2}",model.Code,money,model.Balance));
                }
                //记录日志
                VipCardUseLogHelper.WriteLog(code, "充值"+money +"元", VipCardUseEnum.充值, "", money,CurrentUser.UserName);

                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "充值成功!" + levelMsg });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "充值失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 得到升级后会员等级
        /// </summary>
        /// <param name="curVipLevel">当前会员等级</param>
        /// <param name="rechargeMoney">充值后总金额</param>
        /// <returns></returns>
        public DictionaryModel GetNextVipCardType(DictionaryModel curVipLevel, decimal rechargeMoney)
        {
            //当前等级
            string[] data = curVipLevel.Parameter2.Split(',');
            decimal curLevelMoney = decimal.Parse(data[0]);
            decimal nextLevelMoney = decimal.Parse(data[1]);
            string nextDic_Key = data[2];
            if (nextDic_Key.ToLower() == "toplevel")  //非顶级会员
            {
                return curVipLevel;  //已经是顶级会员，不用升级
            }

            if (rechargeMoney < nextLevelMoney)
            {
                return curVipLevel;  //还没超过当前级别上限，不能升级
            }
            else
            {
                //下一级会员
                DictionaryModel nextVipLevel = db.Dictionarys.GetModel(nextDic_Key);

                //递归判断是否在下一级区间
                return GetNextVipCardType(nextVipLevel, rechargeMoney);
            }
        }

        /// <summary>
        /// 获取会员卡等级列表
        /// </summary>
        /// <returns></returns>
        public JsonResult GetVipCardLevelList()
        {
            List<DictionaryModel> list = db.Dictionarys.GetList(50, "Dic_Key like '103%' and len(Dic_Key)=6", "Dic_Key");
            for (int i = 0; i < list.Count; i++)
            {
                int location = list[i].Parameter2.LastIndexOf(",");
                list[i].Parameter2 = list[i].Parameter2.Substring(0, location);
                list[i].Parameter2 = list[i].Parameter2.Replace(",", " -- ") + " 元";
            }

            return Json(new { data = list });
        }


        public JsonResult IsExists(string cardCode)
        {
            bool result = db.VipCards.Exists(cardCode);
            if (result)
            {
                return Json(new { data = SaveStateEnum.YES.ToString(), msg = "卡号已存在!" });
            }
            else
            {
                return Json(new { data = SaveStateEnum.NO.ToString(), msg = "卡号不存在，可以添加！" });
            }
        }

        public JsonResult GetCardInfo(string code)
        {
            VipCardModel model = db.VipCards.GetModel(code);
            if (model == null)
            {
                return Json(new { code=SaveStateEnum.NO.ToString(), data = model, msg = "卡号不存在!" });
            }
            else
            { 

                 return Json(new {code=SaveStateEnum.OK.ToString(), data = model, msg = "成功" });
            }
        }
    }
}
